<template>
  <PageLayout
    title="主机管理"
    subtitle="管理和监控您的服务器资源"
    icon="fa fa-server"
    class="apply-glass-theme"
  >
    <template #toolbar-left>
      <el-button v-permission="'write'" type="primary" @click="showAddDialog" class="tech-button">
        <i class="fa fa-plus"></i> 添加主机
      </el-button>
      <el-button v-permission="'write'" type="success" @click="showImportDialog" class="tech-button">
        <i class="fa fa-upload"></i> 导入Excel
      </el-button>
      <el-button type="info" @click="downloadTemplate" class="tech-button">
        <i class="fa fa-download"></i> 下载模板
      </el-button>
      <el-button type="warning" @click="exportExcel" class="tech-button">
        <i class="fa fa-file-excel-o"></i> 导出Excel
      </el-button>
    </template>

    <!-- 工具栏右侧 -->
    <template #toolbar-right>
      <el-input
        v-model="searchText"
        placeholder="搜索主机名、IP地址或备注..."
        clearable
        class="tech-input"
        style="width: 350px"
      >
        <template #prefix>
          <i class="fa fa-search"></i>
        </template>
      </el-input>

      <el-dropdown @command="handleRefreshCommand">
        <el-button class="tech-button" :loading="refreshing">
          <i class="fa fa-refresh"></i> 刷新
          <i class="fa fa-caret-down" style="margin-left: 4px;"></i>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="refresh-data">
              <i class="fa fa-refresh"></i> 刷新页面
            </el-dropdown-item>
            <el-dropdown-item command="refresh-all" divided>
              <i class="fa fa-sync-alt"></i> 刷新在线主机信息
            </el-dropdown-item>
            <el-dropdown-item command="batch-refresh" :disabled="selectedHosts.length === 0">
              <i class="fa fa-redo"></i> 批量刷新选中主机 ({{ selectedHosts.length }})
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 自动刷新设置 -->
      <div class="auto-refresh-settings" style="display: flex; align-items: center; gap: 8px; margin-left: 12px;">
        <el-tooltip :content="autoRefreshEnabled ? '停止自动刷新' : '启动自动刷新'" placement="top">
          <el-button
            :type="autoRefreshEnabled ? 'success' : 'info'"
            @click="toggleAutoRefresh"
            class="tech-button"
            size="default"
          >
            <i :class="autoRefreshEnabled ? 'fa fa-pause' : 'fa fa-play'"></i>
            {{ autoRefreshEnabled ? '停止' : '启动' }}
          </el-button>
        </el-tooltip>

        <el-select
          v-model="refreshInterval"
          @change="updateRefreshInterval"
          placeholder="刷新间隔"
          style="width: 120px;"
          class="tech-input refresh-interval-select"
          size="default"
          popper-class="refresh-interval-dropdown"
        >
          <el-option label="5秒" :value="5"></el-option>
          <el-option label="10秒" :value="10"></el-option>
          <el-option label="30秒" :value="30"></el-option>
          <el-option label="1分钟" :value="60"></el-option>
          <el-option label="2分钟" :value="120"></el-option>
          <el-option label="5分钟" :value="300"></el-option>
          <el-option label="10分钟" :value="600"></el-option>
        </el-select>

        <span v-if="autoRefreshEnabled" class="refresh-status" style="color: #00eaff; font-size: 12px;">
          <i class="fa fa-clock"></i>
          倒计时: {{ countdown }}秒
        </span>
      </div>
    </template>

    <!-- 主要内容 -->
    <template #content>
      <div class="glass-card">
        <el-table
          ref="hostTableRef"
          :data="filteredHosts"
          v-loading="loading"
          class="glass-dialog tech-table"
          stripe
          border
          height="calc(100vh - 380px)"
          style="width: 100%;"
          table-layout="fixed"
          @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="hostname" label="主机名" width="120" sortable fixed="left" header-align="center">
          <template #default="scope">
            <div class="hostname-cell">
              <i :class="getTypeIcon(scope.row.type)" class="host-icon" :style="{ color: getTypeColor(scope.row.type) }"></i>
              <span class="hostname-text">{{ scope.row.hostname }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="public_ip" label="公网IP" width="120" sortable align="center" header-align="center" />
        <el-table-column prop="private_ip" label="内网IP" width="120" align="center" header-align="center">
          <template #default="scope">
            <span v-if="scope.row.private_ip && scope.row.private_ip !== '-'" class="ip-text">{{ scope.row.private_ip }}</span>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="140" align="center" header-align="center">
          <template #default="scope">
            <el-tag
              :class="['custom-type-tag', `type-${scope.row.type}`]"
              size="small"
            >
              <i :class="getTypeIcon(scope.row.type)" :style="{ color: getTypeColor(scope.row.type) }"></i>
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center" header-align="center">
          <template #default="scope">
            <div class="status-cell">
              <div :class="['status-indicator', scope.row.status]"></div>
              <span>{{ scope.row.status === 'online' ? '在线' : '离线' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="system_type" label="系统类型" min-width="100" align="center" header-align="center">
          <template #default="scope">
            <div v-if="getDisplaySystemType(scope.row)" class="system-type-cell">
              <i :class="getSystemIcon(getDisplaySystemType(scope.row))" class="system-icon"></i>
              <span>{{ getDisplaySystemType(scope.row) }}</span>
            </div>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="os_version" label="系统版本" min-width="90" align="center" header-align="center">
          <template #default="scope">
            <span v-if="getDisplaySystemVersion(scope.row)" class="version-tag">{{ getDisplaySystemVersion(scope.row) }}</span>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="cpu" label="CPU核心" min-width="90" align="center" header-align="center">
          <template #default="scope">
            <span v-if="scope.row.cpu" class="cpu-cores">{{ scope.row.cpu }}</span>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="cpu_arch" label="CPU架构" min-width="90" align="center" header-align="center">
          <template #default="scope">
            <span v-if="scope.row.cpu_arch" class="arch-tag">{{ scope.row.cpu_arch }}</span>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="memory" label="内存信息" min-width="90" align="center" header-align="center">
          <template #default="scope">
            <span v-if="scope.row.memory" class="hardware-detail">{{ scope.row.memory }}</span>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="disk" label="磁盘信息" min-width="90" align="center" header-align="center">
          <template #default="scope">
            <span v-if="scope.row.disk" class="hardware-detail">{{ scope.row.disk }}</span>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="host_group_names" label="主机组" min-width="120" align="center" header-align="center">
          <template #default="scope">
            <div v-if="scope.row.host_group_names && scope.row.host_group_names.length > 0">
              <!-- 如果只有一个主机组，直接显示 -->
              <div v-if="scope.row.host_group_names.length === 1" class="single-group">
                <el-tag
                  :class="['group-tag', `group-${getGroupColorClass(scope.row.host_group_names[0], 0)}`]"
                  size="small"
                >
                  {{ scope.row.host_group_names[0] }}
                </el-tag>
              </div>
              <!-- 如果有多个主机组，整个区域都可以悬浮 -->
              <el-popover
                v-else
                placement="top"
                width="350"
                trigger="hover"
                popper-class="host-group-popover"
              >
                <template #reference>
                  <div class="host-groups-container">
                    <el-tag
                      :class="['group-tag', `group-${getGroupColorClass(scope.row.host_group_names[0], 0)}`]"
                      size="small"
                    >
                      {{ scope.row.host_group_names[0] }}
                    </el-tag>
                    <el-tag
                      size="small"
                      class="group-tag group-more"
                    >
                      +{{ scope.row.host_group_names.length - 1 }}
                    </el-tag>
                  </div>
                </template>
                <div class="group-detail">
                  <h4 style="color: #00eaff; margin: 0 0 12px 0;">{{ scope.row.hostname }} - 主机组列表</h4>
                  <div class="group-list">
                    <el-tag
                      v-for="groupName in scope.row.host_group_names"
                      :key="groupName"
                      size="small"
                      :class="['group-tag', `group-${getGroupColorClass(groupName, scope.row.host_group_names.indexOf(groupName))}`]"
                      style="margin-right: 6px; margin-bottom: 6px;"
                    >
                      {{ groupName }}
                    </el-tag>
                  </div>
                  <div style="margin-top: 8px; font-size: 12px; color: rgba(255,255,255,0.7);">
                    总计：{{ scope.row.host_group_names.length }} 个主机组
                  </div>
                </div>
              </el-popover>
            </div>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <div class="action-buttons">
            <div class="action-buttons">
              <el-tooltip content="SSH终端" placement="top">
                <el-button size="small" type="primary" @click="openNewSSH(scope.row)" class="action-btn">
                  <i class="fa fa-terminal"></i>
                </el-button>
              </el-tooltip>
              <el-tooltip content="详细信息" placement="top">
                <el-button size="small" type="info" @click="viewHostDetail(scope.row)" class="action-btn">
                  <i class="fa fa-info-circle"></i>
                </el-button>
              </el-tooltip>
              <el-tooltip content="刷新信息" placement="top">
                <el-button size="small" type="success" @click="refreshSingleHost(scope.row)" class="action-btn">
                  <i class="fa fa-refresh"></i>
                </el-button>
              </el-tooltip>
              <el-tooltip v-permission="'write'" content="编辑主机" placement="top">
                <el-button size="small" type="warning" @click="editHost(scope.row)" class="action-btn">
                  <i class="fa fa-edit"></i>
                </el-button>
              </el-tooltip>
              <el-tooltip v-permission="'write'" content="删除主机" placement="top">
                <el-button size="small" type="danger" @click="deleteHost(scope.row)" class="action-btn">
                  <i class="fa fa-trash"></i>
                </el-button>
              </el-tooltip>
            </div>
            </div>
          </template>
        </el-table-column>
        </el-table>
      </div>
    </template>

    <!-- 对话框 -->
    <template #dialogs>
      <!-- 添加/编辑主机对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑主机' : '添加主机'"
        width="650px"
        class="tech-dialog"
        @closed="onDialogClosed"
      >
        <el-form :model="hostForm" :rules="hostRules" ref="hostFormRef" label-width="100px" class="tech-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="主机名" prop="hostname">
                <el-input v-model="hostForm.hostname" placeholder="请输入主机名" class="tech-input" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主机类型" prop="type">
                <el-select v-model="hostForm.type" placeholder="请选择主机类型" style="width: 100%" class="tech-input">
                  <!-- 自定义主机类型 -->
                  <el-option
                    v-for="hostType in hostTypes"
                    :key="hostType.name"
                    :label="hostType.display_name"
                    :value="hostType.name"
                  >
                    <div style="display: flex; align-items: center; gap: 8px;">
                      <i :class="`fas ${hostType.icon}`" :style="{ color: hostType.color }"></i>
                      <span>{{ hostType.display_name }}</span>
                    </div>
                  </el-option>
                  <!-- 默认主机类型（如果没有自定义类型） -->
                  <template v-if="hostTypes.length === 0">
                    <el-option label="Web服务器" value="web">
                      <div style="display: flex; align-items: center; gap: 8px;">
                        <i class="fa fa-globe" style="color: #409eff;"></i>
                        <span>Web服务器</span>
                      </div>
                    </el-option>
                    <el-option label="数据库" value="db">
                      <div style="display: flex; align-items: center; gap: 8px;">
                        <i class="fa fa-database" style="color: #67c23a;"></i>
                        <span>数据库</span>
                      </div>
                    </el-option>
                    <el-option label="应用服务器" value="app">
                      <div style="display: flex; align-items: center; gap: 8px;">
                        <i class="fa fa-cogs" style="color: #e6a23c;"></i>
                        <span>应用服务器</span>
                      </div>
                    </el-option>
                    <el-option label="缓存服务器" value="cache">
                      <div style="display: flex; align-items: center; gap: 8px;">
                        <i class="fa fa-bolt" style="color: #f56c6c;"></i>
                        <span>缓存服务器</span>
                      </div>
                    </el-option>
                    <el-option label="其他" value="other">
                      <div style="display: flex; align-items: center; gap: 8px;">
                        <i class="fa fa-server" style="color: #909399;"></i>
                        <span>其他</span>
                      </div>
                    </el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="公网IP" prop="public_ip">
                <el-input v-model="hostForm.public_ip" placeholder="请输入公网IP地址" class="tech-input" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="内网IP" prop="private_ip">
                <el-input v-model="hostForm.private_ip" placeholder="请输入内网IP地址" class="tech-input" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="端口" prop="port">
                <el-input-number v-model="hostForm.port" :min="1" :max="65535" style="width: 100%" class="tech-input" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="hostForm.username" placeholder="请输入用户名" class="tech-input" />
              </el-form-item>
            </el-col>
          </el-row>

        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="认证方式" prop="auth_type">
              <el-radio-group v-model="hostForm.auth_type" class="auth-radio-group" size="default">
                <el-radio value="password" class="tech-radio">密码认证</el-radio>
                <el-radio value="key" class="tech-radio">密钥认证</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16" v-if="hostForm.auth_type === 'password'">
          <el-col :span="24">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="hostForm.password"
                type="password"
                :placeholder="isEdit ? '留空保持原密码不变，填写则更新密码' : '请输入密码'"
                show-password
                size="default" />
              <div v-if="isEdit" class="form-tip">
                <i class="fa fa-info-circle"></i>
                编辑模式：留空保持原密码不变，填写新密码则更新
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16" v-if="hostForm.auth_type === 'key'">
          <el-col :span="24">
            <el-form-item label="私钥" prop="private_key">
              <el-input
                v-model="hostForm.private_key"
                type="textarea"
                :rows="3"
                :placeholder="isEdit ? '留空保持原私钥不变，填写则更新私钥' : '请输入私钥内容'"
                size="default" />
              <div v-if="isEdit" class="form-tip">
                <i class="fa fa-info-circle"></i>
                编辑模式：留空保持原私钥不变，填写新私钥则更新
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16" v-if="hostForm.auth_type === 'key'">
          <el-col :span="24">
            <el-form-item label="私钥密码" prop="passphrase">
              <el-input
                v-model="hostForm.passphrase"
                type="password"
                :placeholder="isEdit ? '留空保持原密码不变（可选）' : '私钥密码（可选）'"
                show-password
                size="default" />
              <div v-if="isEdit" class="form-tip">
                <i class="fa fa-info-circle"></i>
                编辑模式：留空保持原私钥密码不变
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="所属主机组" prop="host_groups">
              <el-select
                v-model="hostForm.host_groups"
                multiple
                placeholder="请选择主机组（可多选）"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="group in hostGroups"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                >
                  <span>{{ group.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ group.environment_display }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="hostForm.remark" type="textarea" :rows="2" placeholder="请输入备注信息" size="default" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 系统信息 -->
        <el-divider content-position="left">
          <span style="color: #00eaff; font-weight: bold;">
            <i class="fa fa-info-circle"></i> 系统信息
          </span>
          <el-button
            v-if="isEdit"
            size="small"
            type="info"
            @click="autoDetectInfo"
            :loading="detecting"
            style="margin-left: 20px;"
            class="tech-button"
          >
            <i class="fa fa-magic"></i>
            自动检测
          </el-button>
        </el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作系统" prop="os">
              <el-input v-model="hostForm.os" placeholder="如：CentOS、Ubuntu" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统版本" prop="os_version">
              <el-input v-model="hostForm.os_version" placeholder="如：7.9、20.04" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="系统类型" prop="system_type">
              <el-select v-model="hostForm.system_type" placeholder="请选择系统类型" style="width: 100%">
                <el-option label="Linux" value="Linux" />
                <el-option label="Windows" value="Windows" />
                <el-option label="macOS" value="macOS" />
                <el-option label="Unix" value="Unix" />
                <el-option label="其他" value="Other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="CPU架构" prop="cpu_arch">
              <el-select v-model="hostForm.cpu_arch" placeholder="请选择CPU架构" style="width: 100%">
                <el-option label="x86_64" value="x86_64" />
                <el-option label="aarch64" value="aarch64" />
                <el-option label="i386" value="i386" />
                <el-option label="arm" value="arm" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 硬件信息 -->
        <el-divider content-position="left">
          <span style="color: #00eaff; font-weight: bold;">
            <i class="fa fa-microchip"></i> 硬件信息
          </span>
        </el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="CPU信息" prop="cpu_info">
              <el-input v-model="hostForm.cpu_info" placeholder="如：Intel Xeon E5-2680 v4" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="CPU核心数" prop="cpu">
              <el-input v-model="hostForm.cpu" placeholder="如：8核" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="内存信息" prop="memory_info">
              <el-input v-model="hostForm.memory_info" placeholder="如：DDR4 2400MHz" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内存大小" prop="memory">
              <el-input v-model="hostForm.memory" placeholder="如：16GB" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="磁盘信息" prop="disk_info">
              <el-input v-model="hostForm.disk_info" placeholder="如：SSD 500GB" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="磁盘大小" prop="disk">
              <el-input v-model="hostForm.disk" placeholder="如：500GB" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="系统环境" prop="system_environment">
          <el-input v-model="hostForm.system_environment" placeholder="如：生产环境、测试环境、开发环境" />
        </el-form-item>
      </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false" class="tech-button">取消</el-button>
            <el-button type="primary" @click="submitForm" class="tech-button" :loading="submitting">
              <i class="fa fa-save"></i>
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 主机详细信息对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="主机详细信息"
        width="800px"
        class="tech-dialog"
      >
      <div v-if="selectedHost" class="host-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="主机名">
            <div class="detail-value">
              <i :class="getTypeIcon(selectedHost.type)" :style="{ color: getTypeColor(selectedHost.type) }"></i>
              {{ selectedHost.hostname }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="主机类型">
            <el-tag
              :class="['custom-type-tag', `type-${selectedHost.type}`]"
              size="small"
            >
              <i :class="getTypeIcon(selectedHost.type)" :style="{ color: getTypeColor(selectedHost.type) }"></i>
              {{ getTypeText(selectedHost.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="公网IP">
            <span class="ip-content">{{ selectedHost.public_ip }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="内网IP">
            <span class="ip-content">{{ selectedHost.private_ip || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="端口">
            <span class="port-content">{{ selectedHost.port }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="用户名">
            <span class="username-content">{{ selectedHost.username }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <div class="status-cell">
              <div :class="['status-indicator', selectedHost.status]"></div>
              <span>{{ selectedHost.status === 'online' ? '在线' : '离线' }}</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="认证方式">
            <span class="auth-content">{{ selectedHost.auth_type === 'password' ? '密码' : '密钥' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="系统类型">
            <div v-if="getDisplaySystemType(selectedHost)" class="system-type-cell">
              <i :class="getSystemIcon(getDisplaySystemType(selectedHost))" class="system-icon"></i>
              <span>{{ getDisplaySystemType(selectedHost) }}</span>
            </div>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="系统版本">
            <span class="version-content">{{ getDisplaySystemVersion(selectedHost) || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="CPU信息">
            <span class="hardware-content">{{ selectedHost.cpu_info || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="CPU架构">
            <span class="hardware-content">{{ selectedHost.cpu_arch || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="内存信息">
            <span class="hardware-content">{{ selectedHost.memory_info || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="磁盘信息">
            <span class="hardware-content">{{ selectedHost.disk_info || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="系统环境">
            <el-tag v-if="selectedHost.system_environment" size="small" :type="getEnvColor(selectedHost.system_environment)">
              {{ selectedHost.system_environment }}
            </el-tag>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            <span class="time-content">{{ formatDate(selectedHost.created_at) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ selectedHost.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false" class="tech-button-secondary">关闭</el-button>
          <el-button type="success" @click="testConnection(selectedHost)" class="tech-button">
            <i class="fa fa-plug"></i>
            测试连接
          </el-button>
          <el-button type="warning" @click="editHost(selectedHost)" class="tech-button">
            <i class="fa fa-edit"></i>
            编辑主机
          </el-button>
        </div>
      </template>
    </el-dialog>

      <!-- 导入Excel对话框 -->
      <el-dialog
        v-model="importDialogVisible"
        title="导入Excel文件"
        width="500px"
        class="tech-dialog"
      >
      <div class="import-container">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :on-change="handleFileChange"
          :show-file-list="true"
          accept=".xlsx,.xls"
          drag
          class="upload-demo"
        >
          <div class="upload-content">
            <i class="fa fa-cloud-upload upload-icon"></i>
            <div class="upload-text">将Excel文件拖到此处，或<em>点击上传</em></div>
            <div class="upload-tip">只能上传xlsx/xls文件，且不超过10MB</div>
          </div>
        </el-upload>

        <div class="import-tips">
          <h4>导入说明：</h4>
          <ul>
            <li>请先下载模板文件，按照模板格式填写主机信息</li>
            <li>必填字段：主机名、公网IP、端口、用户名、认证方式</li>
            <li>认证方式只能填写：password 或 key</li>
            <li>主机类型可选：web、db、app、cache、other</li>
            <li><strong>智能功能：</strong>只需填写基本连接信息（IP、用户名、密码/密钥），系统会自动获取其他信息</li>
            <li>系统信息（CPU、内存、磁盘、操作系统等）会在导入后自动检测并填充</li>
          </ul>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false" class="tech-button-secondary">取消</el-button>
          <el-button type="primary" @click="importExcel" class="tech-button" :loading="importing">
            <i class="fa fa-upload"></i>
            开始导入
          </el-button>
        </div>
        </template>
      </el-dialog>
    </template>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/components/PageLayout.vue'
import { useAppStore } from '@/stores'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import * as XLSX from 'xlsx'
const router = useRouter()
const route = useRoute()
const store = useAppStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const importing = ref(false)
const detecting = ref(false)
const refreshing = ref(false)
const searchText = ref('')
const refreshTimer = ref(null)
const autoRefreshEnabled = ref(false)
const refreshInterval = ref(15) // 默认15秒，更快响应状态变化
const nextRefreshTime = ref('')
const countdown = ref(0)
const hosts = ref([])
const dialogVisible = ref(false)

// 强制刷新下拉菜单样式（修复版本，不影响内容显示）
const forceRefreshDropdownStyles = () => {
  // 延迟执行，确保DOM已更新
  setTimeout(() => {
    // 只查找特定的下拉菜单，避免影响刷新间隔下拉菜单
    const dropdowns = document.querySelectorAll('.el-select-dropdown:not(.refresh-interval-dropdown)')
    dropdowns.forEach(dropdown => {
      const items = dropdown.querySelectorAll('.el-select-dropdown__item')
      items.forEach(item => {
        const element = item as HTMLElement
        // 只修改样式相关的属性，不修改内容相关的属性
        element.style.color = 'rgba(255, 255, 255, 0.9)'
        element.style.background = 'transparent'
        element.style.borderRadius = '8px'
        element.style.margin = '2px 6px'
        element.style.padding = '8px 12px'
        element.style.fontSize = '14px'
        element.style.lineHeight = '1.4'
        element.style.transition = 'all 0.3s ease'
        // 不修改 display、visibility、opacity 等可能影响内容显示的属性
      })
    })
  }, 100)
}

// 强制刷新图标颜色（修复图标颜色不一致问题）
const forceRefreshIconColors = () => {
  setTimeout(() => {
    // 强制刷新主机名列的图标颜色
    const hostnameIcons = document.querySelectorAll('.hostname-cell .host-icon')
    hostnameIcons.forEach(icon => {
      const element = icon as HTMLElement
      // 强制重新应用颜色
      const currentColor = element.style.color
      element.style.color = ''
      element.offsetHeight // 触发重排
      element.style.color = currentColor
    })

    // 强制刷新类型列的图标颜色
    const typeIcons = document.querySelectorAll('.custom-type-tag i')
    typeIcons.forEach(icon => {
      const element = icon as HTMLElement
      // 强制重新应用颜色
      const currentColor = element.style.color
      element.style.color = ''
      element.offsetHeight // 触发重排
      element.style.color = currentColor
    })
  }, 100)
}

// 对话框关闭时的处理
const onDialogClosed = () => {
  // 只刷新图标颜色，不刷新下拉菜单样式（避免影响刷新间隔下拉菜单）
  forceRefreshIconColors()
}

const importDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const isEdit = ref(false)
const hostFormRef = ref()
const hostTableRef = ref()
const uploadRef = ref()
const selectedFile = ref(null)
const selectedHost = ref(null)
const selectedHosts = ref<any[]>([])
const hostGroups = ref([])
const hostTypes = ref([])



// 主机表单数据
const hostForm = ref({
  hostname: '',
  public_ip: '',
  private_ip: '',
  port: 22,
  username: 'root',
  auth_type: 'password',
  password: '',
  private_key: '',
  passphrase: '',
  type: 'web',
  remark: '',
  status: 'offline',
  host_groups: [],
  // 系统信息
  os: '',
  os_version: '',
  system_type: '',
  cpu_arch: '',
  system_environment: '',
  // 硬件信息
  cpu: '',
  cpu_info: '',
  memory: '',
  memory_info: '',
  disk: '',
  disk_info: ''
})

// 表单验证规则
const hostRules = {
  hostname: [
    { min: 2, max: 50, message: '主机名长度在 2 到 50 个字符', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        if (!value) return callback()
        // 检查主机名唯一性
        const existingHost = hosts.value.find(host =>
          host.hostname === value && (!isEdit.value || host.id !== hostForm.value.id)
        )
        if (existingHost) {
          callback(new Error('主机名已存在，请使用其他名称'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  public_ip: [
    { required: true, message: '请输入公网IP地址', trigger: 'blur' },
    { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: '请输入正确的IP地址格式', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        if (!value) return callback()
        // 检查公网IP唯一性
        const existingHost = hosts.value.find(host =>
          host.public_ip === value && (!isEdit.value || host.id !== hostForm.value.id)
        )
        if (existingHost) {
          callback(new Error('公网IP已存在，请使用其他IP地址'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  private_ip: [
    { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: '请输入正确的IP地址格式', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        if (!value) return callback()
        // 检查内网IP唯一性
        const existingHost = hosts.value.find(host =>
          host.private_ip === value && (!isEdit.value || host.id !== hostForm.value.id)
        )
        if (existingHost) {
          callback(new Error('内网IP已存在，请使用其他IP地址'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口号范围为 1-65535', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  auth_type: [
    { required: true, message: '请选择认证方式', trigger: 'change' }
  ],
  password: [
    {
      validator: (rule, value, callback) => {
        // 新建模式下，如果认证方式是密码且密码为空，则报错
        if (hostForm.value.auth_type === 'password' && !value && !isEdit.value) {
          callback(new Error('请输入密码'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  private_key: [
    {
      validator: (rule, value, callback) => {
        // 编辑模式下，如果私钥为空且认证方式是密钥，则不验证（保持原私钥）
        if (hostForm.value.auth_type === 'key' && !value && !isEdit.value) {
          callback(new Error('请输入私钥'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const filteredHosts = computed(() => {
  let result = hosts.value

  // 先进行搜索过滤
  if (searchText.value) {
    result = result.filter(host =>
      host.hostname?.toLowerCase().includes(searchText.value.toLowerCase()) ||
      host.public_ip?.includes(searchText.value) ||
      host.private_ip?.includes(searchText.value) ||
      host.remark?.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }

  // 然后进行排序：优先按主机名排序，其次按公网IP排序
  return result.sort((a, b) => {
    // 首先按主机名排序（从小到大）
    const hostnameA = (a.hostname || '').toLowerCase()
    const hostnameB = (b.hostname || '').toLowerCase()

    if (hostnameA < hostnameB) return -1
    if (hostnameA > hostnameB) return 1

    // 主机名相同时，按公网IP排序（从小到大）
    const ipA = a.public_ip || ''
    const ipB = b.public_ip || ''

    // IP地址排序需要特殊处理，按数字大小而不是字符串
    const ipPartsA = ipA.split('.').map(part => parseInt(part) || 0)
    const ipPartsB = ipB.split('.').map(part => parseInt(part) || 0)

    for (let i = 0; i < 4; i++) {
      if (ipPartsA[i] < ipPartsB[i]) return -1
      if (ipPartsA[i] > ipPartsB[i]) return 1
    }

    return 0
  })
})

// 创建响应式的主机类型映射
const hostTypeMap = computed(() => {
  const map = new Map()
  hostTypes.value.forEach(type => {
    map.set(type.name, type)
  })
  return map
})

const onlineHosts = computed(() => {
  return hosts.value.filter(host => host.status === 'online').length
})

const offlineHosts = computed(() => {
  return hosts.value.filter(host => host.status === 'offline').length
})

// 工具函数

const getTypeText = (type: string) => {
  // 使用响应式映射进行精确匹配
  const hostType = hostTypeMap.value.get(type)

  if (hostType) {
    return hostType.display_name
  }

  // 如果映射匹配失败，尝试模糊匹配
  const fuzzyMatch = hostTypes.value.find(t =>
    t.name.toLowerCase() === type.toLowerCase() ||
    t.display_name.toLowerCase() === type.toLowerCase() ||
    t.name.replace(/[_-]/g, '') === type.replace(/[_-]/g, '') ||
    t.display_name.replace(/[_-\s]/g, '') === type.replace(/[_-\s]/g, '')
  )

  if (fuzzyMatch) {
    return fuzzyMatch.display_name
  }

  // 如果没找到，使用默认映射
  const texts = {
    web: 'Web服务器',
    db: '数据库',
    app: '应用服务器',
    cache: '缓存服务器',
    other: '其他'
  }
  return texts[type] || '未知'
}

const getTypeIcon = (type: string) => {
  // 使用响应式映射进行精确匹配
  const hostType = hostTypeMap.value.get(type)

  if (hostType) {
    return `fas ${hostType.icon}`
  }

  // 如果映射匹配失败，尝试模糊匹配
  const fuzzyMatch = hostTypes.value.find(t =>
    t.name.toLowerCase() === type.toLowerCase() ||
    t.display_name.toLowerCase() === type.toLowerCase() ||
    t.name.replace(/[_-]/g, '') === type.replace(/[_-]/g, '') ||
    t.display_name.replace(/[_-\s]/g, '') === type.replace(/[_-\s]/g, '')
  )

  if (fuzzyMatch) {
    return `fas ${fuzzyMatch.icon}`
  }

  // 如果没找到，使用默认映射
  const icons = {
    web: 'fa fa-globe',
    db: 'fa fa-database',
    app: 'fa fa-cogs',
    cache: 'fa fa-bolt',
    other: 'fa fa-server'
  }
  return icons[type] || 'fa fa-server'
}

const getTypeColor = (type: string) => {
  // 使用响应式映射进行精确匹配
  const hostType = hostTypeMap.value.get(type)

  if (hostType) {
    return hostType.color
  }

  // 如果映射匹配失败，尝试模糊匹配
  const fuzzyMatch = hostTypes.value.find(t =>
    t.name.toLowerCase() === type.toLowerCase() ||
    t.display_name.toLowerCase() === type.toLowerCase() ||
    t.name.replace(/[_-]/g, '') === type.replace(/[_-]/g, '') ||
    t.display_name.replace(/[_-\s]/g, '') === type.replace(/[_-\s]/g, '')
  )

  if (fuzzyMatch) {
    return fuzzyMatch.color
  }

  // 默认颜色
  return '#606266'
}

// 根据主颜色生成浅色背景
const getTypeLightColor = (type: string) => {
  const color = getTypeColor(type)

  // 确保颜色是十六进制格式
  if (!color || !color.startsWith('#')) {
    return 'rgba(96, 98, 102, 0.15)' // 默认浅灰色
  }

  // 将十六进制颜色转换为RGB
  const hex = color.replace('#', '')

  // 处理3位和6位十六进制颜色
  let r, g, b
  if (hex.length === 3) {
    r = parseInt(hex[0] + hex[0], 16)
    g = parseInt(hex[1] + hex[1], 16)
    b = parseInt(hex[2] + hex[2], 16)
  } else if (hex.length === 6) {
    r = parseInt(hex.substr(0, 2), 16)
    g = parseInt(hex.substr(2, 2), 16)
    b = parseInt(hex.substr(4, 2), 16)
  } else {
    return 'rgba(96, 98, 102, 0.15)' // 默认浅灰色
  }

  // 生成浅色版本（15%透明度）
  return `rgba(${r}, ${g}, ${b}, 0.15)`
}

const getEnvColor = (env: string) => {
  const colors = {
    '生产环境': 'danger',
    '测试环境': 'warning',
    '开发环境': 'success',
    '预发布环境': 'info',
    '演示环境': 'primary'
  }
  return colors[env] || 'default'
}

const getGroupColorClass = (groupName: string, index: number) => {
  // 根据主机组名称生成一个稳定的颜色类
  const colors = ['primary', 'success', 'warning', 'info', 'danger', 'purple', 'cyan', 'orange']
  let hash = 0
  for (let i = 0; i < groupName.length; i++) {
    hash = groupName.charCodeAt(i) + ((hash << 5) - hash)
  }
  return colors[Math.abs(hash) % colors.length]
}

const getSystemIcon = (system: string) => {
  if (!system) return 'fa fa-question-circle'

  const systemLower = system.toLowerCase()
  const icons = {
    'linux': 'fab fa-linux',
    'ubuntu': 'fab fa-ubuntu',
    'centos': 'fab fa-centos',
    'redhat': 'fab fa-redhat',
    'debian': 'fab fa-debian',
    'windows': 'fab fa-windows',
    'macos': 'fab fa-apple',
    'unix': 'fa fa-terminal',
    'freebsd': 'fab fa-freebsd',
    'suse': 'fab fa-suse'
  }

  // 检查系统名称中是否包含关键词
  for (const [key, icon] of Object.entries(icons)) {
    if (systemLower.includes(key)) {
      return icon
    }
  }

  return 'fa fa-server'
}

const getDisplaySystemType = (host: any) => {
  // 从 os_version 字段优先提取系统类型（因为这里可能包含更准确的信息）
  if (host.os_version) {
    const versionLower = host.os_version.toLowerCase()
    if (versionLower.includes('ubuntu')) return 'Ubuntu'
    if (versionLower.includes('centos')) return 'CentOS'
    if (versionLower.includes('redhat') || versionLower.includes('rhel')) return 'RedHat'
    if (versionLower.includes('debian')) return 'Debian'
    if (versionLower.includes('windows')) return 'Windows'
    if (versionLower.includes('suse')) return 'SUSE'
    if (versionLower.includes('fedora')) return 'Fedora'
  }

  // 从 os 字段提取系统类型
  if (host.os) {
    const osLower = host.os.toLowerCase()
    if (osLower.includes('ubuntu')) return 'Ubuntu'
    if (osLower.includes('centos')) return 'CentOS'
    if (osLower.includes('redhat') || osLower.includes('rhel')) return 'RedHat'
    if (osLower.includes('debian')) return 'Debian'
    if (osLower.includes('windows')) return 'Windows'
    if (osLower.includes('macos') || osLower.includes('darwin')) return 'macOS'
    if (osLower.includes('suse')) return 'SUSE'
    if (osLower.includes('fedora')) return 'Fedora'
    // Linux 放在最后，避免覆盖具体的发行版
    if (osLower.includes('linux')) return 'Linux'
    return host.os
  }

  // 最后使用 system_type
  if (host.system_type) {
    return host.system_type
  }

  return ''
}

const getDisplaySystemVersion = (host: any) => {
  // 如果有明确的 os_version 字段，优先使用
  if (host.os_version) {
    // 如果版本号中包含系统名称，提取纯版本号
    const version = host.os_version.toLowerCase()

    // 提取版本号的正则表达式
    const versionPatterns = [
      /(\d+\.\d+(?:\.\d+)?)/,  // 匹配 x.x 或 x.x.x 格式
      /(\d+)/                   // 匹配纯数字
    ]

    for (const pattern of versionPatterns) {
      const match = version.match(pattern)
      if (match) {
        return match[1]
      }
    }

    return host.os_version
  }

  // 如果没有 os_version，尝试从 os 字段提取版本
  if (host.os) {
    const osLower = host.os.toLowerCase()
    const versionMatch = osLower.match(/(\d+\.\d+(?:\.\d+)?)/)
    if (versionMatch) {
      return versionMatch[1]
    }
  }

  return ''
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 数据操作方法
const fetchHosts = async (preserveSelection = false) => {
  loading.value = true
  try {
    // 如果需要保持选择状态，先记录当前选中的主机ID
    const selectedHostIds = preserveSelection ? selectedHosts.value.map(host => host.id) : []

    const response = await store.getHosts()
    hosts.value = response || []

    // 如果需要保持选择状态，重新设置选中的主机
    if (preserveSelection && selectedHostIds.length > 0 && hostTableRef.value) {
      nextTick(() => {
        // 等待DOM更新后，重新设置选中状态
        const newSelectedHosts = hosts.value.filter(host => selectedHostIds.includes(host.id))
        selectedHosts.value = newSelectedHosts

        // 使用表格ref来设置选中状态
        newSelectedHosts.forEach(host => {
          hostTableRef.value.toggleRowSelection(host, true)
        })

        // 强制刷新图标颜色
        forceRefreshIconColors()
      })
    } else {
      // 即使不需要保持选择状态，也要刷新图标颜色
      nextTick(() => {
        forceRefreshIconColors()
      })
    }
  } catch (error) {
    console.error('获取主机列表失败:', error)

    // 如果是429错误（频率限制），只显示警告，不停止自动刷新
    if (error.response?.status === 429) {
      console.warn('请求频率过高，跳过本次刷新')
      if (!preserveSelection) { // 只在非自动刷新时显示错误消息
        ElMessage.warning('请求频率过高，请稍后再试')
      }
    } else if (!preserveSelection) { // 只在非自动刷新时显示错误消息
      ElMessage.error('获取主机列表失败')
    }
  } finally {
    loading.value = false
  }
}

const fetchHostGroups = async () => {
  try {
    const response = await axios.get('/api/hostgroups/')
    console.log('主机组API响应:', response.data)

    // 处理分页响应或直接数组响应
    let groupData = response.data
    if (groupData && typeof groupData === 'object' && groupData.results) {
      // 分页响应
      groupData = groupData.results
    }

    // 确保是数组并过滤掉无效的主机组数据
    if (Array.isArray(groupData)) {
      hostGroups.value = groupData.filter(group => group && group.id)
    } else {
      console.warn('主机组数据不是数组格式:', groupData)
      hostGroups.value = []
    }
  } catch (error) {
    console.error('获取主机组列表失败:', error)
    hostGroups.value = []
  }
}

// 动态添加主机类型CSS样式
const addDynamicTypeStyles = () => {
  // 移除之前的动态样式
  const existingStyle = document.getElementById('dynamic-host-type-styles')
  if (existingStyle) {
    existingStyle.remove()
  }

  // 创建新的样式元素
  const style = document.createElement('style')
  style.id = 'dynamic-host-type-styles'

  let css = ''
  hostTypes.value.forEach(type => {
    const lightColor = getTypeLightColor(type.name)
    css += `
      .el-tag.custom-type-tag.type-${type.name},
      .el-table .el-tag.custom-type-tag.type-${type.name},
      .el-descriptions .el-tag.custom-type-tag.type-${type.name} {
        background: ${lightColor} !important;
        border-color: ${type.color} !important;
        color: ${type.color} !important;
        border: 1px solid ${type.color} !important;
        backdrop-filter: blur(10px) !important;
        transition: all 0.3s ease !important;
        font-weight: 500 !important;
      }

      .el-tag.custom-type-tag.type-${type.name} i,
      .el-table .el-tag.custom-type-tag.type-${type.name} i,
      .el-descriptions .el-tag.custom-type-tag.type-${type.name} i {
        color: ${type.color} !important;
      }
    `
  })

  style.textContent = css
  document.head.appendChild(style)
}

// 获取主机类型列表
const fetchHostTypes = async () => {
  try {
    const response = await axios.get('/api/hosttypes/')
    console.log('主机类型API响应:', response.data)

    // 处理分页响应或直接数组响应
    let typeData = response.data
    if (typeData && typeof typeData === 'object' && typeData.results) {
      // 分页响应
      typeData = typeData.results
    }

    // 确保是数组并过滤掉无效的主机类型数据
    if (Array.isArray(typeData)) {
      hostTypes.value = typeData.filter(type => type && type.id)
      // 动态添加CSS样式
      nextTick(() => {
        addDynamicTypeStyles()
        // 强制刷新图标颜色，确保颜色一致性
        forceRefreshIconColors()
      })
    } else {
      console.warn('主机类型数据不是数组格式:', typeData)
      hostTypes.value = []
    }
  } catch (error) {
    console.error('获取主机类型列表失败:', error)
    hostTypes.value = []
  }
}

const refreshData = () => {
  clearSelection() // 手动刷新时清空选择
  fetchHosts()
  ElMessage.success('数据已刷新')
}

// 刷新命令处理
const handleRefreshCommand = (command: string) => {
  switch (command) {
    case 'refresh-data':
      refreshData()
      break
    case 'refresh-all':
      refreshAllHosts()
      break
    case 'batch-refresh':
      batchRefresh()
      break
  }
}

// 表格选择处理
const handleSelectionChange = (selection: any[]) => {
  selectedHosts.value = selection
}

// 清空选择状态
const clearSelection = () => {
  selectedHosts.value = []
  if (hostTableRef.value) {
    hostTableRef.value.clearSelection()
  }
}

// 主机操作方法
const showAddDialog = () => {
  isEdit.value = false
  resetForm()
  // 新建模式下，设置一个默认密码，用户可以修改
  hostForm.value.password = '123456'
  dialogVisible.value = true
}

const editHost = (host: any) => {
  // 使用 nextTick 确保 DOM 更新完成后再处理数据
  nextTick(() => {
    isEdit.value = true

    // 使用浅拷贝避免深度响应式处理导致的性能问题
    const formData = {
      id: host.id,
      hostname: host.hostname || '',
      public_ip: host.public_ip || '',
      private_ip: host.private_ip || '',
      port: host.port || 22,
      username: host.username || 'root',
      auth_type: host.auth_type || 'password',
      password: '', // 编辑时密码字段为空，用户需要重新输入或保持不变
      private_key: '', // 编辑时私钥字段为空
      passphrase: '', // 编辑时私钥密码字段为空
      type: host.type || 'other',
      remark: host.remark || '',
      status: host.status || 'offline',
      host_groups: Array.isArray(host.host_groups) ? [...host.host_groups] : [],
      // 系统信息
      os: host.os || '',
      os_version: host.os_version || '',
      system_type: host.system_type || '',
      cpu_arch: host.cpu_arch || '',
      system_environment: host.system_environment || '',
      // 硬件信息
      cpu: host.cpu || '',
      cpu_info: host.cpu_info || '',
      memory: host.memory || '',
      memory_info: host.memory_info || '',
      disk: host.disk || '',
      disk_info: host.disk_info || ''
    }

    // 一次性赋值，避免多次触发响应式更新
    Object.assign(hostForm.value, formData)

    // 先显示对话框，再关闭详情对话框，避免同时操作多个对话框
    dialogVisible.value = true

    // 延迟关闭详情对话框，避免冲突
    setTimeout(() => {
      detailDialogVisible.value = false
    }, 50)
  })
}

const viewHostDetail = (host: any) => {
  selectedHost.value = host
  detailDialogVisible.value = true
}

const resetForm = () => {
  // 使用 Object.assign 一次性重置，避免多次触发响应式更新
  const defaultForm = {
    hostname: '',
    public_ip: '',
    private_ip: '',
    port: 22,
    username: 'root',
    auth_type: 'password',
    password: '',
    private_key: '',
    passphrase: '',
    type: 'web',
    remark: '',
    status: 'offline',
    host_groups: [],
    // 系统信息
    os: '',
    os_version: '',
    system_type: '',
    cpu_arch: '',
    system_environment: '',
    // 硬件信息
    cpu: '',
    cpu_info: '',
    memory: '',
    memory_info: '',
    disk: '',
    disk_info: ''
  }

  Object.assign(hostForm.value, defaultForm)

  // 延迟清除验证，避免阻塞UI
  nextTick(() => {
    if (hostFormRef.value) {
      hostFormRef.value.clearValidate()
    }
  })
}

const submitForm = async () => {
  if (!hostFormRef.value) return

  try {
    await hostFormRef.value.validate()
    submitting.value = true

    // 准备提交数据
    const submitData = { ...hostForm.value }

    // 编辑模式下，如果密码字段为空，则不发送密码字段（保持原密码不变）
    if (isEdit.value) {
      if (!submitData.password || submitData.password.trim() === '') {
        delete submitData.password
      }

      if (!submitData.private_key || submitData.private_key.trim() === '') {
        delete submitData.private_key
      }
      if (!submitData.passphrase || submitData.passphrase.trim() === '') {
        delete submitData.passphrase
      }

      await store.updateHost(submitData.id, submitData)
      ElMessage.success('主机更新成功')
    } else {
      await store.createHost(submitData)
      ElMessage.success('主机创建成功')
    }

    dialogVisible.value = false
    clearSelection() // 创建/编辑操作后清空选择

    await fetchHosts()
    // 重新获取主机类型数据，确保最新的类型信息
    await fetchHostTypes()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(isEdit.value ? '主机更新失败' : '主机创建失败')
  } finally {
    submitting.value = false
  }
}

const deleteHost = async (host: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除主机 "${host.hostname}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'tech-message-box'
      }
    )

    await store.deleteHost(host.id)
    ElMessage.success('主机删除成功')
    clearSelection() // 删除操作后清空选择
    await fetchHosts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('主机删除失败')
    }
  }
}

const openNewSSH = async (host: any) => {
  try {
    // 请求SSH访问令牌
    const response = await axios.post('/api/ssh/request-access/', {
      host_id: host.id
    })

    if (response.data.success) {
      // 使用访问令牌跳转到SSH页面
      router.push(`/ssh/${host.id}?token=${response.data.access_token}`)
    } else {
      ElMessage.error(response.data.message || '无权访问此主机')
    }
  } catch (error) {
    console.error('请求SSH访问失败:', error)
    ElMessage.error('请求SSH访问失败，请检查权限')
  }
}

const testConnection = async (host: any) => {
  try {
    ElMessage.info('正在测试连接...')
    const response = await axios.post(`/api/hosts/${host.id}/test/`)
    if (response.data.success) {
      ElMessage.success('连接测试成功')
      // 刷新主机列表以更新状态，保持选择状态
      await fetchHosts(true)
    } else {
      ElMessage.error(`连接测试失败: ${response.data.message}`)
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error('连接测试失败')
  }
}

const autoDetectInfo = async () => {
  if (!hostForm.value.id) {
    ElMessage.warning('请先保存主机信息后再进行自动检测')
    return
  }

  detecting.value = true
  try {
    ElMessage.info('正在自动检测系统信息，请稍候...')
    const response = await axios.post(`/api/hosts/${hostForm.value.id}/detect-info/`)

    if (response.data.success) {
      // 更新表单数据
      const detectedInfo = response.data.detected_info
      if (detectedInfo) {
        Object.keys(detectedInfo).forEach(key => {
          if (hostForm.value.hasOwnProperty(key) && detectedInfo[key]) {
            hostForm.value[key] = detectedInfo[key]
          }
        })
      }

      ElMessage.success('系统信息检测完成')
    } else {
      ElMessage.error(`检测失败: ${response.data.message}`)
    }
  } catch (error) {
    console.error('自动检测失败:', error)
    ElMessage.error('自动检测失败，请检查主机连接')
  } finally {
    detecting.value = false
  }
}

// 刷新功能
const refreshSingleHost = async (host: any) => {
  try {
    ElMessage.info(`正在刷新主机 ${host.hostname} 的信息...`)
    const result = await store.refreshHostInfo(host.id)

    if (result.success) {
      ElMessage.success(result.data.message)
      // 刷新主机列表，保持选择状态
      await fetchHosts(true)
    } else {
      ElMessage.error(result.message || '刷新主机信息失败')
    }
  } catch (error) {
    console.error('刷新主机信息失败:', error)
    ElMessage.error('刷新主机信息失败')
  }
}

const refreshAllHosts = async () => {
  refreshing.value = true
  try {
    ElMessage.info('正在刷新在线主机信息，请稍候...')
    const result = await store.refreshAllHosts()

    if (result.success) {
      ElMessage.success(result.message || '刷新在线主机信息成功')
      // 刷新完成后重新获取主机列表，保持选择状态
      await fetchHosts(true)
    } else {
      ElMessage.error(result.message || '刷新在线主机信息失败')
    }
  } catch (error) {
    console.error('刷新在线主机信息失败:', error)
    ElMessage.error('刷新在线主机信息失败')
  } finally {
    refreshing.value = false
  }
}

const batchRefresh = async () => {
  if (selectedHosts.value.length === 0) {
    ElMessage.warning('请先选择要刷新的主机')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要刷新选中的 ${selectedHosts.value.length} 台主机的信息吗？`,
      '确认批量刷新',
      {
        confirmButtonText: '确定刷新',
        cancelButtonText: '取消',
        type: 'info',
        customClass: 'tech-message-box'
      }
    )

    const hostIds = selectedHosts.value.map(host => host.id)
    ElMessage.info(`正在批量刷新 ${hostIds.length} 台主机信息...`)

    const result = await store.batchRefreshHosts(hostIds)

    if (result.success) {
      ElMessage.success(result.data.message)
      // 批量操作完成后清空选择并刷新数据
      clearSelection()
      // 刷新数据但不保持选择状态
      await fetchHosts(false)
    } else {
      ElMessage.error(result.message || '批量刷新主机信息失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量刷新主机信息失败:', error)
      ElMessage.error('批量刷新主机信息失败')
    }
  }
}

// Excel导入导出功能
const showImportDialog = () => {
  importDialogVisible.value = true
  selectedFile.value = null
}

const handleFileChange = (file: any) => {
  selectedFile.value = file.raw
}

const downloadTemplate = () => {
  // 创建模板数据 - 包含所有数据库字段
  const templateData = [
    {
      'ID': '1',
      '主机名': 'example-web-01',
      '公网IP': '192.168.1.100',
      '内网IP': '10.0.1.100',
      '端口': '22',
      '用户名': 'root',
      '认证方式': '密码',
      '密码': '请填写实际密码',
      '私钥': '',
      '私钥密码': '',
      '主机类型': 'Web服务器',
      '主机组': 'Web服务器组,生产环境组',
      '状态': '离线',
      '操作系统': 'CentOS',
      '系统版本': '7.9',
      '系统类型': 'Linux',
      'CPU信息': 'Intel Xeon E5-2680 v4 @ 2.40GHz',
      'CPU核心': '8核',
      'CPU架构': 'x86_64',
      '内存信息': 'DDR4 2400MHz',
      '内存大小': '16GB',
      '磁盘信息': 'SSD SATA 500GB',
      '磁盘大小': '500GB',
      '系统环境': '生产环境',
      '创建时间': '2024-01-01 10:00:00',
      '更新时间': '2024-01-01 10:00:00',
      '备注': '示例Web服务器'
    },
    {
      'ID': '2',
      '主机名': 'example-db-01',
      '公网IP': '192.168.1.101',
      '内网IP': '10.0.1.101',
      '端口': '22',
      '用户名': 'root',
      '认证方式': '密钥',
      '密码': '',
      '私钥': '请粘贴完整的私钥内容',
      '私钥密码': '私钥密码(如有)',
      '主机类型': '数据库服务器',
      '主机组': '数据库组,核心服务组',
      '状态': '离线',
      '操作系统': 'Ubuntu',
      '系统版本': '20.04',
      '系统类型': 'Linux',
      'CPU信息': 'AMD EPYC 7742 @ 2.25GHz',
      'CPU核心': '16核',
      'CPU架构': 'x86_64',
      '内存信息': 'DDR4 3200MHz',
      '内存大小': '32GB',
      '磁盘信息': 'NVMe SSD 1TB',
      '磁盘大小': '1TB',
      '系统环境': '生产环境',
      '创建时间': '2024-01-01 10:00:00',
      '更新时间': '2024-01-01 10:00:00',
      '备注': '示例数据库服务器'
    }
  ]

  // 直接使用HTML方式导出，不再使用XLSX



  // 使用HTML方式导出，确保样式在WPS中正确显示
  const templateHeaders = Object.keys(templateData[0])

  // 创建HTML表格
  let htmlContent = `
    <html>
    <head>
      <meta charset="UTF-8">
      <style>
        body { font-family: '微软雅黑', Arial, sans-serif; margin: 20px; }
        table {
          border-collapse: collapse;
          width: 100%;
          border: 2px solid #000;
        }
        td {
          border: 1px solid #000 !important;
          border-collapse: collapse;
        }
        .title {
          background-color: #70AD47;
          color: white;
          font-weight: bold;
          font-size: 16px;
          text-align: center;
          padding: 12px;
          border: 1px solid #000 !important;
        }
        .header {
          background-color: #E2EFDA;
          color: black;
          font-weight: bold;
          font-size: 12px;
          text-align: center;
          padding: 8px;
          border: 1px solid #000 !important;
        }
        .data {
          text-align: center;
          padding: 6px;
          font-size: 11px;
          border: 1px solid #000 !important;
          background-color: #F2F2F2;
        }
      </style>
    </head>
    <body>
      <table>
        <tr>
          <td colspan="${templateHeaders.length}" class="title">上海AiOps云计算集训营 主机信息导入模板 By DriverZeng（曾老湿）</td>
        </tr>
        <tr>
          ${templateHeaders.map(header => `<td class="header">${header}</td>`).join('')}
        </tr>
  `

  // 添加数据行
  templateData.forEach((row) => {
    htmlContent += `
        <tr>
          ${templateHeaders.map(header => `<td class="data">${row[header] || ''}</td>`).join('')}
        </tr>
    `
  })

  htmlContent += `
      </table>
      <br><br>
      <h3>填写说明：</h3>
      <table style="width: 80%;">
        <tr>
          <td class="title" colspan="3">填写说明</td>
        </tr>
        <tr>
          <td class="header">字段名</td>
          <td class="header">说明</td>
          <td class="header">示例</td>
        </tr>
        <tr>
          <td class="data">主机组</td>
          <td class="data" style="text-align: left;">多个主机组用英文逗号分隔</td>
          <td class="data">Web服务器组,生产环境组</td>
        </tr>
        <tr>
          <td class="data">认证方式</td>
          <td class="data" style="text-align: left;">填写"密码"或"密钥"</td>
          <td class="data">密码</td>
        </tr>
        <tr>
          <td class="data">密码</td>
          <td class="data" style="text-align: left;">认证方式为"密码"时必填，请填写实际密码</td>
          <td class="data">your_actual_password</td>
        </tr>
        <tr>
          <td class="data">私钥</td>
          <td class="data" style="text-align: left;">认证方式为"密钥"时必填，粘贴完整私钥内容</td>
          <td class="data">-----BEGIN RSA PRIVATE KEY-----...</td>
        </tr>
        <tr>
          <td class="data">主机类型</td>
          <td class="data" style="text-align: left;">请使用系统中已配置的主机类型名称</td>
          <td class="data">Web服务器</td>
        </tr>
        <tr>
          <td class="data">端口</td>
          <td class="data" style="text-align: left;">SSH连接端口，默认22</td>
          <td class="data">22</td>
        </tr>
        <tr>
          <td class="data">状态</td>
          <td class="data" style="text-align: left;">导入时默认为"离线"，系统会自动检测</td>
          <td class="data">离线</td>
        </tr>
      </table>
    </body>
    </html>
  `

  // 创建Blob并下载
  const blob = new Blob([htmlContent], { type: 'application/vnd.ms-excel;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `主机信息导入模板_${new Date().toISOString().slice(0, 10)}.xls`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)

  ElMessage.success('模板下载成功')
}

const exportExcel = () => {
  if (hosts.value.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }

  // 准备导出数据
  const exportData = hosts.value.map(host => ({
    'ID': host.id,
    '主机名': host.hostname,
    '公网IP': host.public_ip,
    '内网IP': host.private_ip || '',
    '端口': host.port,
    '用户名': host.username,
    '认证方式': host.auth_type === 'password' ? '密码' : '密钥',
    '密码': host.auth_type === 'password' ? '***' : '',
    '私钥': host.auth_type === 'key' ? '已配置' : '',
    '私钥密码': host.passphrase ? '已配置' : '',
    '主机类型': getTypeText(host.type),
    '主机组': host.host_group_names ? host.host_group_names.join(',') : '',
    '状态': host.status === 'online' ? '在线' : '离线',
    '操作系统': host.os || '',
    '系统版本': host.os_version || '',
    '系统类型': host.system_type || '',
    'CPU信息': host.cpu_info || '',
    'CPU核心': host.cpu || '',
    'CPU架构': host.cpu_arch || '',
    '内存信息': host.memory_info || '',
    '内存大小': host.memory || '',
    '磁盘信息': host.disk_info || '',
    '磁盘大小': host.disk || '',
    '系统环境': host.system_environment || '',
    '创建时间': formatDate(host.created_at),
    '更新时间': formatDate(host.updated_at),
    '备注': host.remark || ''
  }))

  const headers = Object.keys(exportData[0])

  // 创建HTML表格
  let htmlContent = `
    <html>
    <head>
      <meta charset="UTF-8">
      <style>
        body { font-family: '微软雅黑', Arial, sans-serif; margin: 20px; }
        table {
          border-collapse: collapse;
          width: 100%;
          border: 2px solid #000;
        }
        td {
          border: 1px solid #000 !important;
          border-collapse: collapse;
        }
        .title {
          background-color: #4472C4;
          color: white;
          font-weight: bold;
          font-size: 16px;
          text-align: center;
          padding: 12px;
          border: 1px solid #000 !important;
        }
        .header {
          background-color: #D9E2F3;
          color: black;
          font-weight: bold;
          font-size: 12px;
          text-align: center;
          padding: 8px;
          border: 1px solid #000 !important;
        }
        .data {
          text-align: center;
          padding: 6px;
          font-size: 11px;
          border: 1px solid #000 !important;
        }
        .data-even {
          background-color: #F2F2F2;
        }
        .data-odd {
          background-color: #FFFFFF;
        }
      </style>
    </head>
    <body>
      <table>
        <tr>
          <td colspan="${headers.length}" class="title">上海AiOps云计算集训营 By DriverZeng（曾老湿）</td>
        </tr>
        <tr>
          ${headers.map(header => `<td class="header">${header}</td>`).join('')}
        </tr>
  `

  // 添加数据行
  exportData.forEach((row, index) => {
    const rowClass = index % 2 === 0 ? 'data-even' : 'data-odd'
    htmlContent += `
        <tr>
          ${headers.map(header => `<td class="data ${rowClass}">${row[header] || ''}</td>`).join('')}
        </tr>
    `
  })

  htmlContent += `
      </table>
    </body>
    </html>
  `

  // 创建Blob并下载
  const blob = new Blob([htmlContent], { type: 'application/vnd.ms-excel;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `主机信息导出_${new Date().toISOString().slice(0, 10)}.xls`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)

  ElMessage.success('导出成功')
}

const importExcel = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要导入的Excel文件')
    return
  }

  importing.value = true
  try {
    // 读取Excel文件
    const data = await readExcelFile(selectedFile.value)

    if (!data || data.length === 0) {
      ElMessage.error('Excel文件为空或格式不正确')
      return
    }

    // 验证和转换数据
    const validHosts = []
    const errors = []

    for (let i = 0; i < data.length; i++) {
      const row = data[i]
      const rowNum = i + 2 // Excel行号从2开始（第1行是标题）

      try {
        console.log(`处理第${rowNum}行数据:`, row)

        // 清理和提取数据，处理可能的HTML标签或特殊字符
        const cleanText = (text: any, isPassword: boolean = false) => {
          if (!text) return ''
          const str = String(text)

          // 对于密码字段，只去除前后空格，保留所有特殊字符
          if (isPassword) {
            return str.trim()
          }

          // 对于其他字段，去除HTML标签并trim
          return str.replace(/<[^>]*>/g, '').trim()
        }

        // 字段映射，支持多种可能的字段名
        const getFieldValue = (row: any, isPassword: boolean = false, ...fieldNames: string[]) => {
          for (const fieldName of fieldNames) {
            if (row[fieldName] !== undefined && row[fieldName] !== null && row[fieldName] !== '') {
              return cleanText(row[fieldName], isPassword)
            }
          }
          return ''
        }

        // 只验证必要字段：公网IP、端口、用户、连接方式、明文密码
        const publicIp = getFieldValue(row, false, '公网IP', 'IP地址', '主机IP', '外网IP')
        const port = parseInt(getFieldValue(row, false, '端口', 'SSH端口', '连接端口')) || 22
        const username = getFieldValue(row, false, '用户名', '登录用户', '用户') || 'root'
        const authType = getFieldValue(row, false, '认证方式', '登录方式', '连接方式') === '密钥' ? 'key' : 'password'
        const password = getFieldValue(row, true, '密码', '登录密码', '明文密码')  // 密码字段特殊处理



        // 基本必填字段验证
        if (!publicIp) {
          errors.push(`第${rowNum}行：公网IP不能为空`)
          continue
        }

        // IP格式验证
        const ipPattern = /^(\d{1,3}\.){3}\d{1,3}$/
        if (!ipPattern.test(publicIp)) {
          errors.push(`第${rowNum}行：公网IP格式不正确`)
          continue
        }

        // 认证信息验证（只验证密码认证方式）
        if (authType === 'password' && (!password || password === '***' || password === '请填写实际密码')) {
          errors.push(`第${rowNum}行：使用密码认证时，密码字段不能为空`)
          continue
        }

        // 处理主机组（可选，不验证是否存在）
        const hostGroupText = getFieldValue(row, false, '主机组', '所属组', '分组')
        const hostGroupNames = hostGroupText ? hostGroupText.split(',').map(name => name.trim()).filter(name => name) : []
        const hostGroupIds = getHostGroupIdsByNames(hostGroupNames)

        const hostData = {
          hostname: getFieldValue(row, false, '主机名', '服务器名', '设备名') || `host-${publicIp}`, // 如果没有主机名，自动生成
          public_ip: publicIp,
          private_ip: getFieldValue(row, false, '内网IP', '私网IP', '局域网IP') || '',
          port: port,
          username: username,
          auth_type: authType,
          password: password,
          private_key: getFieldValue(row, true, '私钥', 'SSH私钥', '密钥内容') || '',  // 私钥也需要保留特殊字符
          passphrase: getFieldValue(row, true, '私钥密码', '密钥密码', 'passphrase') || '',  // 私钥密码也需要保留特殊字符
          type: getTypeValueFromText(getFieldValue(row, false, '主机类型', '服务器类型', '设备类型')) || 'other',
          host_groups: hostGroupIds,
          // 系统信息（可选，会自动获取）
          os: getFieldValue(row, false, '操作系统', 'OS', '系统') || '',
          system_type: getFieldValue(row, false, '系统类型', 'OS类型') || '',
          os_version: getFieldValue(row, false, '系统版本', 'OS版本', '版本') || '',
          cpu_info: getFieldValue(row, false, 'CPU信息', 'CPU详情', '处理器信息') || '',
          cpu: getFieldValue(row, false, 'CPU核心', 'CPU核数', '核心数') || '',
          cpu_arch: getFieldValue(row, false, 'CPU架构', '处理器架构', '架构') || '',
          memory_info: getFieldValue(row, false, '内存信息', '内存详情', '内存配置') || '',
          memory: getFieldValue(row, false, '内存大小', '内存容量', '内存') || '',
          disk_info: getFieldValue(row, false, '磁盘信息', '磁盘详情', '存储信息') || '',
          disk: getFieldValue(row, false, '磁盘大小', '磁盘容量', '存储容量') || '',
          system_environment: getFieldValue(row, false, '系统环境', '环境', '用途') || '',
          remark: getFieldValue(row, false, '备注', '说明', '描述') || '',
          status: 'offline'
        }

        // 内网IP格式验证（如果有的话）
        if (hostData.private_ip && !ipPattern.test(hostData.private_ip)) {
          errors.push(`第${rowNum}行：内网IP格式不正确`)
          continue
        }

        validHosts.push(hostData)
      } catch (error) {
        errors.push(`第${rowNum}行：数据格式错误`)
      }
    }

    if (errors.length > 0) {
      ElMessage.error(`导入失败，发现 ${errors.length} 个错误：\n${errors.slice(0, 5).join('\n')}${errors.length > 5 ? '\n...' : ''}`)
      return
    }

    // 批量创建主机
    let successCount = 0
    let failCount = 0
    const failedHosts = []
    const skippedHosts = []

    for (const hostData of validHosts) {
      try {
        console.log('正在创建主机:', hostData.hostname, hostData.public_ip)

        // 检查是否已存在相同IP的主机
        const existingHost = hosts.value.find(h => h.public_ip === hostData.public_ip)
        if (existingHost) {
          console.log('主机已存在，跳过:', hostData.hostname, hostData.public_ip)
          skippedHosts.push({
            hostname: hostData.hostname,
            ip: hostData.public_ip,
            reason: `IP地址已存在于主机 ${existingHost.hostname}`
          })
          continue
        }

        const result = await store.createHost(hostData)
        successCount++
        console.log('主机创建成功:', hostData.hostname, result)
      } catch (error) {
        console.error('创建主机失败:', hostData.hostname, error)

        // 检查是否是重复IP错误
        const errorMessage = error.response?.data?.message || error.message || '未知错误'
        if (errorMessage.includes('已存在') || errorMessage.includes('duplicate') || errorMessage.includes('unique')) {
          skippedHosts.push({
            hostname: hostData.hostname,
            ip: hostData.public_ip,
            reason: '主机已存在'
          })
        } else {
          failCount++
          failedHosts.push({
            hostname: hostData.hostname,
            ip: hostData.public_ip,
            error: errorMessage
          })
        }
      }
    }

    console.log('导入结果:', { successCount, failCount, failedHosts, skippedHosts })

    // 显示导入结果
    const totalProcessed = successCount + failCount + skippedHosts.length
    let message = `导入完成！成功：${successCount} 个`

    if (skippedHosts.length > 0) {
      message += `，跳过：${skippedHosts.length} 个`
    }

    if (failCount > 0) {
      message += `，失败：${failCount} 个`
      const failedInfo = failedHosts.slice(0, 3).map(h => `${h.hostname}(${h.ip}): ${h.error}`).join('\n')
      message += `\n失败详情：\n${failedInfo}${failCount > 3 ? '\n...' : ''}`
    }

    if (skippedHosts.length > 0) {
      const skippedInfo = skippedHosts.slice(0, 3).map(h => `${h.hostname}(${h.ip}): ${h.reason}`).join('\n')
      message += `\n跳过详情：\n${skippedInfo}${skippedHosts.length > 3 ? '\n...' : ''}`
    }

    if (failCount > 0 || skippedHosts.length > 0) {
      ElMessage({
        message,
        type: successCount > 0 ? 'warning' : 'error',
        duration: 10000,
        showClose: true
      })
    } else {
      ElMessage.success(message)
    }

    // 安全提示
    if (successCount > 0) {
      setTimeout(() => {
        ElMessage({
          message: '安全提醒：请及时删除包含密码的Excel文件，避免密码泄露',
          type: 'warning',
          duration: 5000
        })
      }, 1000)
    }

    if (successCount > 0) {
      clearSelection() // 导入操作后清空选择
      await fetchHosts()
    }

    importDialogVisible.value = false
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败，请检查文件格式')
  } finally {
    importing.value = false
  }
}

const readExcelFile = (file: File): Promise<any[]> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target?.result as ArrayBuffer)
        const workbook = XLSX.read(data, {
          type: 'array',
          cellText: false,
          cellDates: true,
          raw: true  // 使用原始数据，避免特殊字符被转换
        })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]

        // 获取工作表的范围
        const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1')
        console.log('Excel工作表范围:', range)

        // 手动读取数据，跳过前两行（站点名称和字段名）
        const rawData = []

        // 从第2行开始读取字段名作为表头（索引从0开始，所以第2行是索引1）
        const headers = []
        for (let col = range.s.c; col <= range.e.c; col++) {
          const cellAddress = XLSX.utils.encode_cell({ r: 1, c: col })
          const cell = worksheet[cellAddress]
          if (cell && cell.v) {
            headers.push(String(cell.v).trim())
          }
        }

        console.log('读取到的表头:', headers)

        // 从第3行开始读取数据（索引从0开始，所以第3行是索引2）
        for (let row = 2; row <= range.e.r; row++) {
          const rowData: any = {}
          let hasData = false

          for (let col = range.s.c; col <= range.e.c; col++) {
            const cellAddress = XLSX.utils.encode_cell({ r: row, c: col })
            const cell = worksheet[cellAddress]
            const header = headers[col - range.s.c]

            if (header && cell && cell.v !== undefined && cell.v !== null) {
              // 对于密码相关字段，保留原始值；其他字段进行清理
              let value = String(cell.v)
              const isPasswordField = ['密码', '登录密码', '明文密码', '私钥', 'SSH私钥', '密钥内容', '私钥密码', '密钥密码', 'passphrase'].includes(header)

              if (isPasswordField) {
                // 密码字段只去除前后空格，保留所有特殊字符
                value = value.trim()
              } else {
                // 其他字段去除HTML标签和多余空格
                value = value.replace(/<[^>]*>/g, '').trim()
              }

              rowData[header] = value
              hasData = true
            }
          }

          // 只添加有数据的行
          if (hasData) {
            rawData.push(rowData)
          }
        }

        console.log('读取到的原始数据:', rawData)

        // 进一步过滤，确保至少有公网IP
        const filteredData = rawData.filter((row: any) => {
          const publicIp = row['公网IP'] || row['IP地址'] || row['主机IP']
          return publicIp && publicIp.trim() && !publicIp.includes('请填写')
        })

        console.log('过滤后的有效数据:', filteredData)
        resolve(filteredData)
      } catch (error) {
        console.error('读取Excel文件失败:', error)
        reject(error)
      }
    }
    reader.onerror = reject
    reader.readAsArrayBuffer(file)
  })
}

const getTypeValueFromText = (text: string) => {
  // 首先尝试从自定义主机类型中查找
  const customType = hostTypes.value.find(type =>
    type.display_name === text || type.name === text
  )
  if (customType) {
    return customType.name
  }

  // 如果没找到，使用默认映射
  const typeMap = {
    'Web服务器': 'web',
    '数据库': 'db',
    '数据库服务器': 'db',
    '应用服务器': 'app',
    '缓存服务器': 'cache',
    '其他': 'other'
  }
  return typeMap[text] || 'other'
}

// 根据主机组名称获取主机组ID
const getHostGroupIdsByNames = (groupNames: string[]) => {
  const groupIds: number[] = []
  groupNames.forEach(name => {
    const group = hostGroups.value.find(g => g.name === name)
    if (group) {
      groupIds.push(group.id)
    }
  })
  return groupIds
}

// 切换自动刷新状态
const toggleAutoRefresh = () => {
  autoRefreshEnabled.value = !autoRefreshEnabled.value
  if (autoRefreshEnabled.value) {
    startRealTimeRefresh()
    ElMessage.success(`已启动自动刷新，间隔${getIntervalText(refreshInterval.value)}`)
  } else {
    stopRealTimeRefresh()
    ElMessage.info('已停止自动刷新')
  }
}

// 更新刷新间隔
const updateRefreshInterval = (newInterval: number) => {
  refreshInterval.value = newInterval
  if (autoRefreshEnabled.value) {
    // 重新启动定时器
    startRealTimeRefresh()
    ElMessage.success(`刷新间隔已更新为${getIntervalText(newInterval)}`)
  }
}

// 获取间隔文本
const getIntervalText = (seconds: number) => {
  if (seconds < 60) return `${seconds}秒`
  if (seconds < 3600) return `${seconds / 60}分钟`
  return `${seconds / 3600}小时`
}

// 更新倒计时显示
const updateCountdown = () => {
  if (!autoRefreshEnabled.value) {
    countdown.value = 0
    return
  }

  countdown.value--

  if (countdown.value <= 0) {
    countdown.value = refreshInterval.value
  }
}

// 启动实时刷新
const startRealTimeRefresh = () => {
  // 清除现有定时器
  stopRealTimeRefresh()

  // 初始化倒计时
  countdown.value = refreshInterval.value

  // 根据设置的间隔启动定时器
  refreshTimer.value = setInterval(() => {
    fetchHosts(true) // 传入 true 保持选择状态
    countdown.value = refreshInterval.value // 重置倒计时
  }, refreshInterval.value * 1000)

  // 启动倒计时更新（每秒更新一次）
  const countdownTimer = setInterval(() => {
    updateCountdown()
  }, 1000)

  // 保存倒计时定时器引用
  refreshTimer.value.countdownTimer = countdownTimer
}

// 停止实时刷新
const stopRealTimeRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
    if (refreshTimer.value.countdownTimer) {
      clearInterval(refreshTimer.value.countdownTimer)
    }
    refreshTimer.value = null
  }
  countdown.value = 0
  nextRefreshTime.value = ''
}

// 生命周期
onMounted(async () => {
  // 先加载主机类型数据，确保颜色映射正确
  await fetchHostTypes()
  // 然后加载主机数据
  fetchHosts()
  fetchHostGroups()

  // 处理URL参数，如果有主机组筛选参数
  if (route.query.hostgroup) {
    const hostgroupId = route.query.hostgroup
    const hostgroupName = route.query.hostgroup_name || '指定主机组'

    // 显示提示信息
    ElMessage.success(`已筛选主机组：${hostgroupName}`)

    // 这里可以添加筛选逻辑，暂时先显示提示
    console.log('筛选主机组ID:', hostgroupId, '名称:', hostgroupName)
  }

  // 默认不启动自动刷新，由用户手动控制

  // 修复下拉菜单宽度匹配问题（排除刷新间隔下拉菜单）
  setTimeout(() => {
    const fixDropdownWidth = () => {
      // 只处理非刷新间隔的下拉菜单，避免影响刷新间隔下拉菜单
      const selects = document.querySelectorAll('.el-select:not(.refresh-interval-select)')
      selects.forEach(select => {
        const selectWidth = select.offsetWidth
        document.documentElement.style.setProperty('--el-select-width', `${selectWidth}px`)
      })
    }

    // 初始设置
    fixDropdownWidth()

    // 监听窗口大小变化
    window.addEventListener('resize', fixDropdownWidth)

    // 监听DOM变化
    const observer = new MutationObserver(fixDropdownWidth)
    observer.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ['style', 'class']
    })
  }, 200)

  // 强制刷新图标颜色，确保动态颜色生效
  nextTick(() => {
    setTimeout(() => {
      // 强制重新渲染表格，确保图标颜色正确显示
      const table = document.querySelector('.el-table')
      if (table) {
        table.style.display = 'none'
        table.offsetHeight // 触发重排
        table.style.display = ''
      }
    }, 500)
  })
})

// 页面卸载时停止实时刷新
onUnmounted(() => {
  stopRealTimeRefresh()
})
</script>

<style lang="scss" scoped>
// 自动刷新设置样式
.auto-refresh-settings {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 12px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;

  &:hover {
    background: rgba(255, 255, 255, 0.08);
    border-color: rgba(0, 234, 255, 0.3);
  }
}

.refresh-status {
  color: #00eaff;
  font-size: 12px;
  white-space: nowrap;
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;

  i {
    animation: pulse 2s infinite;
  }
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

// 主机管理页面容器样式 - 与主机组管理页面保持一致的深色调
.page-container {
  background: linear-gradient(135deg, #0f1327 0%, #1a2332 100%);
  min-height: 100vh;
  color: #e6e6e6;
}

// 视图切换按钮样式
.view-toggle {
  margin-left: 15px;

  .el-button {
    border-radius: 0 !important;

    &:first-child {
      border-top-left-radius: 8px !important;
      border-bottom-left-radius: 8px !important;
    }

    &:last-child {
      border-top-right-radius: 8px !important;
      border-bottom-right-radius: 8px !important;
    }
  }
}

// 表格视图样式
.host-groups-table {
  .group-name-cell {
    display: flex;
    align-items: center;
    gap: 10px;

    .group-name {
      font-weight: 500;
      color: var(--text-primary);
    }
  }

  .table-actions {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
  }
}

// 强制覆盖对话框中的选择框样式
.el-dialog {
  .el-select {
    .el-input__wrapper {
      background: rgba(255, 255, 255, 0.05) !important;
      border: 1px solid rgba(255, 255, 255, 0.1) !important;
      backdrop-filter: blur(10px) !important;
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

      &:hover {
        border-color: rgba(0, 234, 255, 0.3) !important;
      }

      &.is-focus {
        border-color: #00eaff !important;
        box-shadow:
          inset 0 1px 3px rgba(0, 0, 0, 0.1),
          0 0 10px rgba(0, 234, 255, 0.3) !important;
      }

      .el-input__inner {
        color: white !important;
        background: transparent !important;

        &::placeholder {
          color: rgba(255, 255, 255, 0.5) !important;
        }
      }

      .el-input__suffix {
        .el-input__suffix-inner {
          .el-select__caret {
            color: rgba(255, 255, 255, 0.6) !important;

            &:hover {
              color: #00eaff !important;
            }
          }
        }
      }
    }
  }
}

// 工具栏中的选择框样式
.page-container {
  .el-select {
    .el-input__wrapper {
      background: rgba(255, 255, 255, 0.05) !important;
      border: 1px solid rgba(255, 255, 255, 0.1) !important;
      backdrop-filter: blur(10px) !important;
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

      &:hover {
        border-color: rgba(0, 234, 255, 0.3) !important;
      }

      &.is-focus {
        border-color: #00eaff !important;
        box-shadow:
          inset 0 1px 3px rgba(0, 0, 0, 0.1),
          0 0 10px rgba(0, 234, 255, 0.3) !important;
      }

      .el-input__inner {
        color: white !important;
        background: transparent !important;

        &::placeholder {
          color: rgba(255, 255, 255, 0.5) !important;
        }
      }

      .el-input__suffix {
        .el-input__suffix-inner {
          .el-select__caret {
            color: rgba(255, 255, 255, 0.6) !important;

            &:hover {
              color: #00eaff !important;
            }
          }
        }
      }
    }
  }
}

// 修复下拉菜单滚动条问题 - 使用全局样式

// 主机组网格布局
.host-groups-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.host-group-card {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(20px);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  color: white;

  &:hover {
    transform: translateY(-5px);
    background: rgba(255, 255, 255, 0.08);
    border-color: rgba(0, 234, 255, 0.3);
    box-shadow:
      0 12px 40px rgba(0, 0, 0, 0.15),
      0 0 20px rgba(0, 234, 255, 0.2),
      inset 0 1px 0 rgba(255, 255, 255, 0.2);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;

  .group-info h3 {
    margin: 0 0 5px 0;
    color: white;
    font-size: 1.2rem;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
}

.environment-tag {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  color: white;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);

  &.dev {
    background: linear-gradient(135deg, #409eff, #5dade2);
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  }
  &.test {
    background: linear-gradient(135deg, #67c23a, #82e7ab);
    box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
  }
  &.staging {
    background: linear-gradient(135deg, #e6a23c, #f4d03f);
    box-shadow: 0 2px 8px rgba(230, 162, 60, 0.3);
  }
  &.prod {
    background: linear-gradient(135deg, #f56c6c, #ff7675);
    box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
  }
}

.stats {
  display: flex;
  gap: 15px;
  margin: 15px 0;

  .stat-item {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 0.9rem;
    color: rgba(255, 255, 255, 0.8);

    i {
      color: #00eaff;
      text-shadow: 0 0 5px rgba(0, 234, 255, 0.5);
    }
  }
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  font-size: 0.8rem;
  color: rgba(255, 255, 255, 0.7);

  .owner-info, .create-time {
    display: flex;
    align-items: center;
    gap: 5px;

    i {
      color: #00eaff;
      text-shadow: 0 0 5px rgba(0, 234, 255, 0.5);
    }
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: white;

  i {
    font-size: 4rem;
    margin-bottom: 20px;
    opacity: 0.6;
    color: #00eaff;
    text-shadow: 0 0 20px rgba(0, 234, 255, 0.5);
  }

  h3 {
    margin-bottom: 10px;
    font-size: 1.5rem;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }

  p {
    opacity: 0.8;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  }
}

// 对话框样式覆盖
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  backdrop-filter: blur(20px) !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  .el-dialog__header {
    background: transparent !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;

    .el-dialog__title {
      color: white !important;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3) !important;
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: rgba(255, 255, 255, 0.8) !important;

      &:hover {
        color: #00eaff !important;
      }
    }
  }

  .el-dialog__body {
    background: transparent !important;
    color: white !important;
  }

  .el-dialog__footer {
    background: transparent !important;
    border-top: 1px solid rgba(255, 255, 255, 0.1) !important;
  }
}

// 表单样式
:deep(.el-form) {
  .el-form-item__label {
    color: rgba(255, 255, 255, 0.9) !important;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
  }

  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(10px) !important;
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &.is-focus {
      border-color: #00eaff !important;
      box-shadow:
        inset 0 1px 3px rgba(0, 0, 0, 0.1),
        0 0 10px rgba(0, 234, 255, 0.3) !important;
    }

    .el-input__inner {
      color: white !important;
      background: transparent !important;

      &::placeholder {
        color: rgba(255, 255, 255, 0.5) !important;
      }
    }
  }

  .el-select {
    .el-input__wrapper {
      background: rgba(0, 50, 100, 0.8) !important;
      border: 1px solid rgba(255, 255, 255, 0.1) !important;
      backdrop-filter: blur(10px) !important;
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

      &:hover {
        border-color: rgba(0, 234, 255, 0.3) !important;
      }

      &.is-focus {
        border-color: #00eaff !important;
        box-shadow:
          inset 0 1px 3px rgba(0, 0, 0, 0.1),
          0 0 10px rgba(0, 234, 255, 0.3) !important;
      }

      .el-input__inner {
        color: white !important;
        background: transparent !important;

        &::placeholder {
          color: rgba(255, 255, 255, 0.5) !important;
        }
      }

      .el-input__suffix {
        .el-input__suffix-inner {
          .el-select__caret {
            color: rgba(255, 255, 255, 0.6) !important;

            &:hover {
              color: #00eaff !important;
            }
          }
        }
      }
    }

    .el-select__placeholder {
      color: rgba(255, 255, 255, 0.5) !important;
    }
  }

  .el-textarea__inner {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    color: white !important;
    backdrop-filter: blur(10px) !important;

    &::placeholder {
      color: rgba(255, 255, 255, 0.5) !important;
    }

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &:focus {
      border-color: #00eaff !important;
      box-shadow: 0 0 10px rgba(0, 234, 255, 0.3) !important;
    }
  }
}

// 按钮样式
:deep(.el-button) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: white !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;

  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
  }

  &.el-button--primary {
    background: linear-gradient(135deg, #00eaff, #0099cc) !important;
    border-color: #00eaff !important;
    box-shadow: 0 4px 15px rgba(0, 234, 255, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, #33f0ff, #00b8e6) !important;
      box-shadow: 0 6px 20px rgba(0, 234, 255, 0.4) !important;
    }
  }
}

// 标签样式
:deep(.el-tag) {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  color: white !important;
  backdrop-filter: blur(10px) !important;
}



// 下拉菜单箭头样式保留，用于工具栏下拉菜单
:deep(.el-dropdown-menu) {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
  border-radius: 12px !important;

  .el-dropdown-menu__item {
    color: rgba(255, 255, 255, 0.9) !important;
    background: transparent !important;
    border-radius: 8px !important;
    margin: 2px 6px !important;
    padding: 8px 12px !important;
    transition: all 0.3s ease !important;

    &:hover {
      background: rgba(0, 234, 255, 0.15) !important;
      color: white !important;
      transform: translateX(2px) !important;
      box-shadow: 0 2px 8px rgba(0, 234, 255, 0.2) !important;
    }

    i {
      color: rgba(0, 234, 255, 0.8) !important;
      margin-right: 6px !important;
    }
  }
}

/* 主机组容器样式 - 水平排列 */
.host-groups-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.host-groups-container:hover {
  background: rgba(164, 244, 186, 0.1);
  transform: translateY(-1px);
}

.single-group {
  display: flex;
  justify-content: center;
}

/* 主机组popover样式已移至global.css */
</style>

<!-- 全局样式修复下拉菜单滚动条问题 -->
<style>
/* 修复Element Plus下拉菜单滚动条问题 */
.el-select-dropdown {
  max-height: 300px !important;
}

.el-select-dropdown .el-scrollbar {
  max-height: 300px !important;
}

.el-select-dropdown .el-scrollbar__wrap {
  max-height: 300px !important;
  overflow-y: auto !important;
}

.el-select-dropdown .el-select-dropdown__list {
  max-height: none !important;
}

/* 确保滚动条可见和样式 */
.el-select-dropdown .el-scrollbar__bar {
  opacity: 1 !important;
  transition: opacity 0.3s ease !important;
}

.el-select-dropdown .el-scrollbar__bar.is-vertical {
  right: 2px !important;
  width: 6px !important;
}

.el-select-dropdown .el-scrollbar__thumb {
  background-color: rgba(0, 234, 255, 0.6) !important;
  border-radius: 4px !important;
}

.el-select-dropdown .el-scrollbar__thumb:hover {
  background-color: rgba(0, 234, 255, 0.8) !important;
}

/* 确保下拉菜单内容可以滚动 */
.el-select-dropdown .el-select-dropdown__wrap {
  max-height: 300px !important;
  overflow: auto !important;
}

// 修复刷新间隔下拉菜单样式问题
.refresh-interval-select {
  .el-select__wrapper {
    background: rgba(255, 255, 255, 0.02) !important;
    border: 1px solid rgba(255, 255, 255, 0.08) !important;
    backdrop-filter: blur(20px) saturate(150%) !important;
  }

  .el-select__placeholder {
    color: rgba(255, 255, 255, 0.6) !important;
  }

  .el-input__inner {
    color: rgba(255, 255, 255, 0.9) !important;
    background: transparent !important;
  }
}

// 全局下拉菜单样式修复
.refresh-interval-dropdown {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
  border-radius: 12px !important;

  .el-select-dropdown__item {
    color: rgba(255, 255, 255, 0.9) !important;
    background: transparent !important;
    border-radius: 8px !important;
    margin: 2px 6px !important;
    padding: 8px 12px !important;
    font-size: 14px !important;
    line-height: 1.4 !important;

    &:hover {
      background: rgba(255, 255, 255, 0.1) !important;
      color: #00eaff !important;
    }

    &.is-selected {
      background: rgba(0, 234, 255, 0.2) !important;
      color: #00eaff !important;
      font-weight: 600 !important;
    }
  }
}

// 确保所有select下拉菜单都有正确的样式 - 使用更高优先级
.el-select-dropdown {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
  border-radius: 12px !important;
  z-index: 9999 !important;

  .el-select-dropdown__item {
    color: rgba(255, 255, 255, 0.9) !important;
    background: transparent !important;
    border-radius: 8px !important;
    margin: 2px 6px !important;
    padding: 8px 12px !important;
    font-size: 14px !important;
    line-height: 1.4 !important;
    min-height: auto !important;
    display: block !important;
    visibility: visible !important;
    opacity: 1 !important;

    &:hover {
      background: rgba(255, 255, 255, 0.1) !important;
      color: #00eaff !important;
    }

    &.is-selected {
      background: rgba(0, 234, 255, 0.2) !important;
      color: #00eaff !important;
      font-weight: 600 !important;
    }
  }
}

/* 移除强制inherit规则，让动态颜色生效 */
/* 注释掉这些规则，让 :style="{ color: getTypeColor(scope.row.type) }" 生效 */
/*
.hostname-cell .host-icon {
  color: inherit !important;
}

.el-tag.custom-type-tag i {
  color: inherit !important;
}
*/

/* import-container 样式修复 - 使用最高优先级覆盖深蓝色背景 */
.el-dialog .import-container,
.tech-dialog .import-container,
.el-dialog__body .import-container,
body .import-container,
html .import-container {
  background: transparent !important;
  background-color: transparent !important;
  padding: 20px !important;
  border-radius: 12px !important;
}
</style>

<!-- 全局样式，确保下拉菜单不受对话框影响 -->
<style>
/* 全局下拉菜单样式保护 - 最高优先级 */
.el-select-dropdown,
.refresh-interval-dropdown {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
  border-radius: 12px !important;
  z-index: 9999 !important;
}

.el-select-dropdown .el-select-dropdown__item,
.refresh-interval-dropdown .el-select-dropdown__item {
  color: rgba(255, 255, 255, 0.9) !important;
  background: transparent !important;
  border-radius: 8px !important;
  margin: 2px 6px !important;
  padding: 8px 12px !important;
  font-size: 14px !important;
  line-height: 1.4 !important;
  min-height: auto !important;
  display: block !important;
  visibility: visible !important;
  opacity: 1 !important;
  white-space: nowrap !important;
}

.el-select-dropdown .el-select-dropdown__item:hover,
.refresh-interval-dropdown .el-select-dropdown__item:hover {
  background: rgba(255, 255, 255, 0.1) !important;
  color: #00eaff !important;
}

.el-select-dropdown .el-select-dropdown__item.is-selected,
.refresh-interval-dropdown .el-select-dropdown__item.is-selected {
  background: rgba(0, 234, 255, 0.2) !important;
  color: #00eaff !important;
  font-weight: 600 !important;
}

/* 确保下拉菜单容器可见 */
.el-select-dropdown__wrap {
  max-height: 274px !important;
  overflow: auto !important;
}

.el-select-dropdown__list {
  padding: 6px 0 !important;
}

/* 防止对话框样式影响下拉菜单 */
.el-dialog .el-select-dropdown,
.el-dialog .refresh-interval-dropdown {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
}

.el-dialog .el-select-dropdown .el-select-dropdown__item,
.el-dialog .refresh-interval-dropdown .el-select-dropdown__item {
  color: rgba(255, 255, 255, 0.9) !important;
  background: transparent !important;
  display: block !important;
  visibility: visible !important;
  opacity: 1 !important;
}


</style>


